import { http } from '@/utils/axios'
import { getCurWebsite } from '@/views/common'

const tplWrapper = (name, content) => {
  return `
    <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <title>${name}</title>
        <style>
          * { margin: 0; padding: 0; }
          body { padding: 10px !important; }
          h1 { padding-bottom: 15px !important; }
        </style>
      </head>
      <body>
        ${content}
      </body>
    </html>
  `
}

const searchCodeKey = 'yongyingSearchCode'
const loginLink = 'yongyingLoginLink'

export default {
  data () {
    return {
      currentSearchCode: '',
      loginLink: ''
    }
  },

  mounted () {
    this.currentSearchCode = localStorage.getItem(searchCodeKey) || ''
    this.loginLink = localStorage.getItem(loginLink) || ''
  },

  methods: {
    loginLinkChange (value) {
      this.loginLink = value
      localStorage.setItem(loginLink, value)
    },
    searchCodeChange (value) {
      localStorage.setItem(searchCodeKey, value)
      this.currentSearchCode = value
    },
    getYongyingItemData (item, index) {
      if (!this.currentSearchCode) {
        return this.$message.error('搜索码为空，请输入搜索码')
      }
      this.loading = true
      this.$set(this.accountList[index], 'statusText', '请求中...')
      this._getYongyingItem(item)
        .then(res => {
          let { name, data } = res
          if (this.startDate && this.endDate) {
            name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
          }
          const tplData = tplWrapper(name, `
            <h1>${name}</h1>
            <div>${data}</div>
          `)
          this.sendToMainProcess(`${name}.html`, tplData)
          this.$set(this.accountList[index], 'statusText', '请求成功')
        })
        .catch(e => {
          console.log('e')
          console.log(e)
          this.$set(this.accountList[index], 'statusText', e || '请求失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getAllYongyingData (reGetList) {
      if (!this.currentSearchCode) {
        return this.$message.error('搜索码为空，请输入搜索码')
      }
      this.loading = true
      const list = reGetList || this.accountList
      const len = list.length
      let index = 0
      const callback = () => {
        if (this.waitExportList.length === 0) {
          return this.$message.info('请求数据为空')
        }
        let name = this.waitExportList.map(e => e.name).join('、')
        if (this.startDate && this.endDate) {
          name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
        }
        console.log(this.waitExportList)
        const tpl = this.waitExportList.map(item => {
          return `
            <h1>${item.name}</h1>
            <div>${item.data}</div>
          `
        })
        const tplData = tplWrapper(name, tpl.join('<br />'))
        this.sendToMainProcess(`${name}.html`, tplData)
        this.loading = false
      }
      for (let i = 0; i < len; i++) {
        const item = list[i]
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getYongyingItem(item)
          .then(res => {
            const { name, data } = res
            this.waitExportList.push({
              name,
              data
            })
            this.$set(this.accountList[itemIndex], 'statusText', '请求成功')
          })
          .catch(error => {
            console.error(error)
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', error && typeof error === 'string' ? error : '请求失败')
          })
          .finally(() => {
            index = index + 1
            if (index === len) {
              this.loading = false
              this.checkExistErrorList(() => callback())
            }
          })
      }
    },
    _getYongyingItem (item) {
      return new Promise((resolve, reject) => {
        const { name, psw, code } = item
        const children = this.getChilren(item.children)
        const { startDate, endDate } = this
        const baseUrl = getCurWebsite()
        const url = baseUrl + '/yongying/gen'
        // eslint-disable-next-line eqeqeq
        const data = {
          username: name,
          pwd: psw,
          safecode: code,
          searchCode: this.currentSearchCode,
          loginLink: this.loginLink,
          date_start: startDate,
          date_end: endDate,
          children: children && children.length ? children : []
        }
        http({
          method: 'post',
          url,
          withCredentials: false,
          data
        }).then(res => {
          if (this.checkSuccess(res)) {
            const data = res.data.data.data
            const result = {
              name,
              data
            }
            resolve(result)
          } else {
            console.log(res)
            reject(res && res.data && res.data.data)
          }
        }).catch(e => {
          console.error('Report Error: ', e)
          reject(e)
        })
      })
    }
  }
}
